package com.itheima.filter;

import com.alibaba.fastjson.JSON;

import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 13613
 */
@Slf4j
@WebFilter("/*")
@Component
public class LoginCheckFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
    //路径匹配器，支持通配符
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求:{}", requestURI);
        //资源放行：登录相关的、退出登录相关的、静态资源【html、css 、js 、图片】
        String[] urls = new String[]{
               "/user/login",
               "/user/sendMsg",
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/common/**",
                "/front/**"
        };
        //antPathMatcher.match(匹配的规则, 具体的路径);
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String url : urls) {
            boolean match = antPathMatcher.match(url, requestURI);
            if (match) {
                log.info("本次请求{}不需要处理",requestURI);
                filterChain.doFilter(request, response);
                return;
            }
        }


            if ( request.getSession().getAttribute("employee")!= null
            || request.getSession().getAttribute("user")!= null)
            {
                log.info("用户已登录，用户id为：{}",  request.getSession().getAttribute("employee"));
                Long empId = (Long) request.getSession().getAttribute("employee");
                Long user = (Long) request.getSession().getAttribute("user");
                if(empId!=null){
                    BaseContext.setCurrentId(empId);
                    System.out.println(empId+"empId---------------------");
                }
                if(user!=null){
                    BaseContext.setCurrentId(user);
                    System.out.println(user+"user---------------------");
                }

                filterChain.doFilter(request, response);

            } else {
                log.info("用户未登录");
                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

            }



    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
